var user_role = sessionStorage.getItem('user_role')
var user_id = sessionStorage.getItem('user_id')
let table_div = document.getElementById('datatable_tab')
let task_div = document.getElementById('task_datatable_tab')
let member_div = document.getElementById('member_datatable_tab')
let upgrade_div = document.getElementById('update_progress')
let btn1 = document.getElementById('datatable_project_export_button')
let btn2 = document.getElementById('datatable_project_print_button')
let btn3 = document.getElementById('datatable_project_static_button')

// 显示界面
function showPage() {
  let user_manage = document.getElementById('user_manage')
  let project_manage = document.getElementById('project_manage')
  let money = document.getElementById('money')
  let contract = document.getElementById('contract')
  if (user_role == '组员') {
    user_manage.style.display = 'none'
    project_manage.style.display = 'none'
    money.style.display = 'none'
    contract.style.display = 'none'
  }
}
showPage()

updateProgress = function (id, p_name, content, progress) {
  console.log(id, p_name, content)
  var showName = p_name === 'undefined' ? '任务: ' + content : '项目: ' + p_name
  $('#projectOrTask').val(showName)
  $('#newProgress').val(progress)
  $('#update_progress').modal('show')
  $('#add_submit_button').on('click', function () {
    let new_progress = document.getElementById('newProgress').value
    new_progress = parseInt(new_progress)
    if (new_progress < 0 || new_progress > 100) {
      alert('请输入0~100之间的整数!')
      $('#newProgress').val(progress)
    } else {
      let r = confirm('确定要更新进度吗？')
      if (r) {
        //更新项目进度
        if (p_name !== 'undefined' && content === 'undefined') {
          var data = {}
          data.leaderID = id
          data.progress = new_progress
          data.action = 'update_project_progress'
          $.post('../project/action1', data, function (json) {
            json = JSON.parse(json)
            console.log(json)
            if (json.result === 1) {
              alert('更新成功！')
              document.location.reload()
            }
            if (json.result === 0) {
              alert('更新失败！')
            }
          })
        }
        //更新任务进度
        else {
          var data = {}
          data.id = id
          data.progress = new_progress
          data.action = 'update_task_progress'
          $.post('../project/action1', data, function (json) {
            json = JSON.parse(json)
            if (json.result === 1) {
              alert('更新成功！')
              document.location.reload()
            }
            if (json.result === 0) {
              alert('更新失败！')
            }
          })
        }
      } else {
        document.location.reload()
      }
    }
  })
}
pageInit = function () {
  $('.datatable').dataTable({
    autoWidth: true,
    paging: true,
    searching: true,
    aaSorting: [], //不让其按第一列排序
    oLanguage: {
      aria: {
        sortAscending: ': activate to sort column ascending',
        sortDescending: ': activate to sort column descending',
      },
      sProcessing: '处理中...',
      sLengthMenu: '_MENU_ 记录/页',
      sZeroRecords: '没有匹配的记录',
      sInfo: '显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项',
      sInfoEmpty: '显示第 0 至 0 项记录，共 0 项',
      sInfoFiltered: '(由 _MAX_ 项记录过滤)',
      sInfoPostFix: '',
      sSearch: '请输入查询信息:',
      oPaginate: {
        sFirst: '首页',
        sPrevious: '上页',
        sNext: '下页',
        sLast: '末页',
      },
    },
    // "aoColumnDefs": [{"bSearchable": false,"bVisible":false,"aTargets":[0]}],
    aoColumns: [
      {
        mRender: function (data, type, full) {
          sReturn = full.project_name
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.leader_name
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.start_time
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.due_time
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          var done = parseInt(full.progress)
          sReturn = "<div style='width: 100%; background-color: darkgrey'>"
          sReturn =
            sReturn +
            "<div style='width: " +
            done +
            "%; background-color: #00BE67; color: white; text-align: center'>" +
            done +
            '%</div></div>'
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn =
            "<button class='btn btn-xs btn-primary' onclick=\"updateProgress(" +
            full.id +
            ",'" +
            full.project_name +
            "','" +
            full.content +
            "'," +
            full.progress +
            ')">更新</button>'
          return sReturn
        },
        orderable: true,
      },
    ],
    aLengthMenu: [
      [5, 10, 15, 20, 25, 40, 50, -1],
      [5, 10, 15, 20, 25, 40, 50, '所有记录'],
    ],
    fnDrawCallback: function () {
      $('.checkboxes').uniform()
      $('.groupDao.java-checkable').uniform()
    },

    ajax: {
      async: false,
      url: '../project/action',
      type: 'POST',
      data: {
        user_role: this.user_role,
        user_id: this.user_id,
        action: 'get_project_info',
      },
      dataSrc: function (result) {
        return result.project_list
      },
    },
  })
  $('.datatable')
    .find('.groupDao.java-checkable')
    .change(function () {
      var set = jQuery(this).attr('data-set')
      var checked = jQuery(this).is(':checked')
      jQuery(set).each(function () {
        if (checked) {
          $(this).attr('checked', true)
          $(this).parents('tr').addClass('active')
        } else {
          $(this).attr('checked', false)
          $(this).parents('tr').removeClass('active')
        }
      })
      jQuery.uniform.update(set)
    })
  $('.datatable').on('change', 'tbody tr .checkboxes', function () {
    $(this).parents('tr').toggleClass('active')
  })
}

//打印用户信息
printUserInfo = function () {
  document
    .getElementById('datatable_project_print_button')
    .addEventListener('click', function () {
      let userObj = {}
      let users = []
      var data = $('.datatable').DataTable().rows({ filter: 'applied' }).data()
      for (let i = 0; i < data.length; i++) {
        users.push(data[i])
      }
      userObj.userList = users
      console.log(userObj)
      sessionStorage.setItem('userObj', JSON.stringify(userObj))
      window.open('./printInfo.html', '_blank')
    })
}
///统计
staticUserInfo = function () {
  document
    .getElementById('datatable_project_static_button')
    .addEventListener('click', function () {
      let userObj = {}
      let users = []
      var data = $('.datatable').DataTable().rows({ filter: 'applied' }).data()
      for (let i = 0; i < data.length; i++) {
        users.push(data[i])
      }
      userObj.userList = users
      console.log(userObj)
      sessionStorage.setItem('userObj', JSON.stringify(userObj))
      window.open('./static.html', '_blank')
    })
}
////撤销任务
deleteTask = function (id) {
  var r = confirm('确定撤销该任务？')
  if (r) {
    var data = {}
    data.id = id
    data.action = 'delete_task'
    $.post('../project/action1', data, function (json) {
      json = JSON.parse(json)
      console.log(json)
      if (json.result === 1) {
        alert('撤销成功！')
        document.location.reload()
      }
      if (json.result === 0) {
        alert('撤销失败！')
      }
    })
  }
}
memberTableInit = function () {
  $('.member_table').dataTable({
    autoWidth: true,
    paging: true,
    searching: true,
    aaSorting: [], //不让其按第一列排序
    oLanguage: {
      aria: {
        sortAscending: ': activate to sort column ascending',
        sortDescending: ': activate to sort column descending',
      },
      sProcessing: '处理中...',
      sLengthMenu: '_MENU_ 记录/页',
      sZeroRecords: '没有匹配的记录',
      sInfo: '显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项',
      sInfoEmpty: '显示第 0 至 0 项记录，共 0 项',
      sInfoFiltered: '(由 _MAX_ 项记录过滤)',
      sInfoPostFix: '',
      sSearch: '请输入查询信息:',
      oPaginate: {
        sFirst: '首页',
        sPrevious: '上页',
        sNext: '下页',
        sLast: '末页',
      },
    },
    // "aoColumnDefs": [{"bSearchable": false,"bVisible":false,"aTargets":[0]}],
    aoColumns: [
      {
        mRender: function (data, type, full) {
          sReturn = full.id
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.toWhoName
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.content
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.workload
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          var done = parseInt(full.progress)
          sReturn = "<div style='width: 100%; background-color: darkgrey'>"
          sReturn =
            sReturn +
            "<div style='width: " +
            done +
            "%; background-color: #00BE67; color: white; text-align: center'>" +
            done +
            '%</div></div>'
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn =
            "<button class='btn btn-xs btn-primary' onclick=\"updateProgress(" +
            full.id +
            ",'" +
            full.project_name +
            "','" +
            full.content +
            "'," +
            full.progress +
            ')">更新进度</button>  '
          sReturn =
            sReturn +
            "<button class='btn btn-xs btn-danger' onclick=\"deleteTask(" +
            full.id +
            ')">撤销任务</button>'
          return sReturn
        },
        orderable: true,
      },
    ],
    aLengthMenu: [
      [5, 10, 15, 20, 25, 40, 50, -1],
      [5, 10, 15, 20, 25, 40, 50, '所有记录'],
    ],
    fnDrawCallback: function () {
      $('.checkboxes').uniform()
      $('.groupDao.java-checkable').uniform()
    },

    ajax: {
      async: false,
      url: '../project/action1',
      type: 'POST',
      data: {
        user_role: this.user_role,
        user_id: this.user_id,
        action: 'get_member_progress',
      },
      dataSrc: function (result) {
        return result.aaData
      },
    },
  })
  $('.member_table')
    .find('.groupDao.java-checkable')
    .change(function () {
      var set = jQuery(this).attr('data-set')
      var checked = jQuery(this).is(':checked')
      jQuery(set).each(function () {
        if (checked) {
          $(this).attr('checked', true)
          $(this).parents('tr').addClass('active')
        } else {
          $(this).attr('checked', false)
          $(this).parents('tr').removeClass('active')
        }
      })
      jQuery.uniform.update(set)
    })
  $('.member_table').on('change', 'tbody tr .checkboxes', function () {
    $(this).parents('tr').toggleClass('active')
  })
}

//打印用户信息
memberPrintUserInfo = function () {
  document
    .getElementById('member_datatable_project_print_button')
    .addEventListener('click', function () {
      let userObj = {}
      let users = []
      var data = $('.member_table')
        .DataTable()
        .rows({ filter: 'applied' })
        .data()
      for (let i = 0; i < data.length; i++) {
        users.push(data[i])
      }
      userObj.userList = users
      console.log(userObj)
      sessionStorage.setItem('userObj', JSON.stringify(userObj))
      window.open('./member_printInfo.html', '_blank')
    })
}
///统计
memberStaticUserInfo = function () {
  document
    .getElementById('member_datatable_project_static_button')
    .addEventListener('click', function () {
      let userObj = {}
      let users = []
      var data = $('.member_table')
        .DataTable()
        .rows({ filter: 'applied' })
        .data()
      for (let i = 0; i < data.length; i++) {
        users.push(data[i])
      }
      userObj.userList = users
      console.log(userObj)
      sessionStorage.setItem('userObj', JSON.stringify(userObj))
      window.open('./member_static.html', '_blank')
    })
}
///组员更新
//任务数据获取
taskTableInit = function () {
  $('.task_table').dataTable({
    autoWidth: true,
    paging: true,
    searching: true,
    aaSorting: [], //不让其按第一列排序
    oLanguage: {
      aria: {
        sortAscending: ': activate to sort column ascending',
        sortDescending: ': activate to sort column descending',
      },
      sProcessing: '处理中...',
      sLengthMenu: '_MENU_ 记录/页',
      sZeroRecords: '没有匹配的记录',
      sInfo: '显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项',
      sInfoEmpty: '显示第 0 至 0 项记录，共 0 项',
      sInfoFiltered: '(由 _MAX_ 项记录过滤)',
      sInfoPostFix: '',
      sSearch: '请输入查询信息:',
      oPaginate: {
        sFirst: '首页',
        sPrevious: '上页',
        sNext: '下页',
        sLast: '末页',
      },
    },
    // "aoColumnDefs": [{"bSearchable": false,"bVisible":false,"aTargets":[0]}],
    aoColumns: [
      {
        mRender: function (data, type, full) {
          sReturn = full.id
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.content
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.workload
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          return full.status === 'todo' ? '待完成' : '已完成'
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.startTime
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          sReturn = full.dueTime
          return sReturn
        },
        orderable: true,
      },
      {
        mRender: function (data, type, full) {
          var done = parseInt(full.progress)
          sReturn = "<div style='width: 100%; background-color: darkgrey'>"
          sReturn =
            sReturn +
            "<div style='width: " +
            done +
            "%; background-color: #00BE67; color: white; text-align: center'>" +
            done +
            '%</div></div>'
          return sReturn
        },
        orderable: false,
      },
      {
        mRender: function (data, type, full) {
          sReturn =
            "<button class='btn btn-xs btn-primary' onclick=\"updateProgress(" +
            full.id +
            ",'" +
            full.project_name +
            "','" +
            full.content +
            "'," +
            full.progress +
            ')">更新</button>'
          return sReturn
        },
        orderable: true,
      },
    ],
    aLengthMenu: [
      [5, 10, 15, 20, 25, 40, 50, -1],
      [5, 10, 15, 20, 25, 40, 50, '所有记录'],
    ],
    fnDrawCallback: function () {
      $('.checkboxes').uniform()
      $('.groupDao.java-checkable').uniform()
    },

    ajax: {
      async: false,
      url: '../project/action1',
      type: 'POST',
      data: {
        user_role: this.user_role,
        user_id: this.user_id,
        action: 'get_task_info',
      },
      dataSrc: function (result) {
        return result.aaData
      },
    },
  })
  $('.task_table')
    .find('.groupDao.java-checkable')
    .change(function () {
      var set = jQuery(this).attr('data-set')
      var checked = jQuery(this).is(':checked')
      jQuery(set).each(function () {
        if (checked) {
          $(this).attr('checked', true)
          $(this).parents('tr').addClass('active')
        } else {
          $(this).attr('checked', false)
          $(this).parents('tr').removeClass('active')
        }
      })
      jQuery.uniform.update(set)
    })
  $('.task_table').on('change', 'tbody tr .checkboxes', function () {
    $(this).parents('tr').toggleClass('active')
  })
}
if (user_role === '管理员') {
  member_div.style.display = 'none'
  task_div.style.display = 'none'
  pageInit()
  printUserInfo()
  staticUserInfo()
}
if (user_role === '组长') {
  task_div.style.display = 'none'
  btn1.style.display = 'none'
  btn2.style.display = 'none'
  btn3.style.display = 'none'
  pageInit()
  memberTableInit()
  memberStaticUserInfo()
  memberPrintUserInfo()
}
if (user_role === '组员') {
  table_div.style.display = 'none'
  member_div.style.display = 'none'
  taskTableInit()
}
